﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Xml.Linq;
using Microsoft.Phone.Controls;
namespace ThessalonikiGuide
{
    public partial class Subcats
    {
        XNamespace kml = "http://www.opengis.net/kml/2.2";
        private ItemFlyInAndOutAnimations _flyOutAnimation = new ItemFlyInAndOutAnimations();
        public Subcats()
        {
            InitializeComponent();
        }

        private static int GetPosition(IList<List<string>> list, string name)
        {
            foreach (var item in list.Where(item => item.Contains(name)))
            {
                return 5*list.IndexOf(item) + item.IndexOf(name);
            }
            return -1;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Page1.Back)
            {
                Page1.Back = false;
            }
            else
            {
                Initialize(NavigationContext.QueryString["categ"]);
            }
            base.OnNavigatedTo(e);
        }

        private void Initialize(string name)
        {
            PageTitle.Text = name;
            var scroll = new ScrollViewer();
            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
            for (var x = 0; x < 2; x++)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
            }
            var cats = Subcatlist(name).Where(y => y != null && y != ProperName(name)).ToList();
            var i = 0;
            var j = 0;
            var count = cats.Count();
            if (count <= 0)
            {
                NavigationService.Navigate(new Uri("/Page1.xaml?cat=" + ProperName(name),UriKind.Relative));
                return;
            }
            foreach (var tile in cats.Select(Tile))
            {
                grid.Children.Add(tile);
                Grid.SetColumn(tile, i);
                Grid.SetRow(tile, j);
                if (i == 1)
                {
                    i = 0;
                    j++;
                }
                else
                {
                    grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
                    i++;
                }
            }

            scroll.Content = grid;
            ContentPanel.Children.Add(scroll);

        }

        private static string ProperName(string name)
        {
             var propername = MainPage.Tiles.Where(x => x.Contains(name)).Select(x => MainPage.Names[MainPage.Tiles.IndexOf(x)][x.IndexOf(name)]).FirstOrDefault();
            return propername;
        }

        private IEnumerable<string> Subcatlist(string name)
        {
            var doc = XDocument.Load("poi_thessalonikis.xml").Element("Document");
            var list = new List<string>();
            var subcats = doc.Descendants("Placemark").Where(y => GetPosition(MainPage.Tiles, name) == GetPosition(MainPage.Names, Page1.Simple(y, "newcat"))).Select(y => Page1.Simple(y, "newsubcat")).ToList();
            foreach (var element in subcats)
            {
                if(!list.Contains(element))
                {
                    list.Add(element);
                }
            }
            return list;
        }
        private HubTile Tile(string name)
        {
            var tile = new HubTile
            {
                Title = name,
                Style = (Style)Resources["HubTileStyle0"],
                Margin = new Thickness { Left = 20, Top = 10, Bottom = 10},
                Source = new BitmapImage(new Uri("/Images/" + name + ".jpg", UriKind.Relative)),
            };
            TiltEffect.SetIsTiltEnabled(tile, true);
            tile.Tap += delegate
            { // animate the element, navigating to the new page when the animation finishes
                _flyOutAnimation.ItemFlyOut(tile, () =>
                {
                    NavigationService.Navigate(new Uri("/Page1.xaml?cat=" + name, UriKind.Relative));
                });
            };
            return tile;
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Privacy.xaml",UriKind.Relative));
        }
    }
}